<template> 
  <div id="Login">
    <div class="container">
      <div class="back"><span class="el-icon-back" @click=" Home()">首页</span></div>
      <div class="form-box-right" id="form-box">
        <!--登录-->
        <div v-show="login" class="login-box">
          <h2>Login</h2>
          <p @click="toggle">没有账号？点此注册</p>
          <el-form
            :inline="true"
            :rules="rules"
            :model="log_user"
            ref="log_user"
            label-width="110px"
            size="mini"
          >
            <el-form-item label="用户名：" prop="lname" class="item" >
              <el-input
               clearable
                v-model="log_user.lname"
              ></el-input>
            </el-form-item>
            <el-form-item label="密码：" prop="lpassword" class="item">
              <el-input
                v-model="log_user.lpassword"
                 show-password
                 clearable
              ></el-input>
            </el-form-item>
          </el-form>
           <p @click="changes">忘记密码? &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</p>
          <button @click="submit_user('log_user')">Login</button> 
        </div>
        <!--注册-->
        <div v-show="regist" class="register-box">
          <h2>Regist</h2>
          <p @click="toggle">已有账号？去登入</p>
          <el-form
            :inline="true"
            :rules="rules"
            ref="re_user"
            :model="re_user"
            label-width="110px"
            size="mini"
          >
            <el-form-item label="用户名：" prop="username" class="item">
              <el-input
                v-model="re_user.username"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="邮箱：" prop="email" class="item">
              <el-input 
              v-model="re_user.email"
              clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="密码：" prop="password" class="item">
              <el-input
                v-model="re_user.password"
                show-password  
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="确认密码：" prop="checkPassword" class="item">
              <el-input
                v-model="re_user.checkPassword"
                 show-password
                 clearable
              ></el-input>
            </el-form-item>
          </el-form>
          <button v-on:click="submit_user('re_user')">Regist</button>
        </div>
        <!--修改密码-->
        <div v-show="change" class="change_password">
          <h2>重置密码</h2>
           <p @click="changes">去登入</p>
          <el-form
            :inline="true"
            :rules="rules"
            ref="ch_user"
            :model="ch_user"
            label-width="110px"
            size="mini"
          >
            <el-form-item label="用户名：" prop="n_username" class="item">
              <el-input
                v-model="ch_user.n_username"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="原密码：" prop="n_password" class="item">
              <el-input
                v-model="ch_user.n_password"
                show-password
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="新密码：" prop="npassword" class="item">
              <el-input
                v-model="ch_user.npassword"
                show-password
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="确认密码：" prop="cpassword"  class="item">
              <el-input
                v-model="ch_user.cpassword"
                show-password
                clearable
              ></el-input>
            </el-form-item>
          </el-form>
          <button @click="submit_user('ch_user')">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "Login",
  data() {
     //注册时用户名已存在！
    const rulesUser = (rule, value, callback) => {
      //使用axios进行校验
      this.$axios
        .post(this.baseURL + "check_username/", {
          username: value,
        })
        .then((res) => {
          //请求成功
          if (res.data.code === 1) {
            if (res.data.exists) {
              callback(new Error("用户名已存在！"));
            } else {
              callback();
            }
          } else {
            //请求失败
            callback(new Error("校验用户名后端出现异常！"));
          }
        })
        .catch((err) => {
          //失败则后台打印
          console.log(err);
        });
    };
    //登入时用户名不存在
    const rulesLoguser = (rule, value, callback) => {
      //使用axios进行校验
      this.$axios
        .post(this.baseURL + "check_username/", {
          username: value,
        })
        .then((res) => {
          //请求成功
          if (res.data.code === 1) {
            if (res.data.exists) {
              callback();
            } else {
              callback(new Error("用户名不存在！请重新输入"));
            }
          } else {
            //请求失败
            callback(new Error("校验用户名后端出现异常！"));
          }
        })
        .catch((err) => {
          //失败则后台打印
          console.log(err);
        });
    };
    //两次密码输入一致
    var checkpassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.re_user.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
       activeIndex: "3",
      //登录信息
      login: true,
      log_user: {
        lname: "",
        lpassword: "",
      },
      baseURL: "http://127.0.0.1:8000/",
      lhold: false,
      
      //注册信息
      regist: false,
      re_user:{
        username: "",
        email: "",
        checkPassword: "",
        password: "",
      },
      //新密码的设定
      change: false,
      ch_user:{
        n_username:"",//用户名
        n_password:"",//旧密码（必须是有过正确账号的才可以进行修改密码）
        npassword: "",//设置的新密码
        cpassword: "",//再次输入的密码
      },
      perface: true,
      //输入数据的规范
      rules: {
        //注册
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
          {
            pattern:  /^[0-9A-Za-z_]{5,8}$/,
            message: "由数字、字母、下划线组成的5-8位",
            trigger: "blur",
          },
          //此处验证该用户名是否已存在
          { validator: rulesUser, trigger: "blur" },
        ],
        email: [
          { required: true, message: "邮箱地址不能为空", trigger: "blur" },
          {
            pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
            message: "邮箱地址必须要符合规范",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          {
            pattern:  /^.*(?=.{6,20})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*?]).*$/,
            message: "大、小写字母,数字,特殊字符(6-20)",
            trigger: "blur",
          },
        ],
        checkPassword:[
           { required: true, message: "再次输入的密码不能为空", trigger: "blur" },
          //此处写验证两次密码是否正确
          { validator: checkpassword, trigger: "blur", required: true },
        ],
        //登录，
        lname: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
          //此处写检查用户名是否存在
          { validator: rulesLoguser, trigger: "blur" },
        ],
        lpassword: [
          { required: true, message: "密码不能为空", trigger: "blur" },
        ],
        //修改
        n_username:[
          { required: true, message: "用户名不能为空", trigger: "blur" },
          //此处写检查用户名是否存在
          { validator: rulesLoguser, trigger: "blur" },
        ],
        n_password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          
        ],
        npassword:[
          { required: true, message: "密码不能为空", trigger: "blur" },
          {
            pattern:  /^.*(?=.{6,20})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*?]).*$/,
            message: "大、小写字母,数字,特殊字符(6-20)",
            trigger: "blur",
          },
        ],
        cpassword:[
          { required: true, message: "确认密码不能为空", trigger: "blur" },
        ]
       
      },
    };
  },
  
  methods: {
     Home(){
      this.$router.push('/');
    },
    Search_(){
       this.$router.push("/Search");
    },
     //登录
    dologin() {
      var flag = 0;
      if (this.lname === "") {
        this.$message.error("用户名不能为空");
      } else if (this.lpassword === "") {
        this.$message.error("密码不能为空");
      } else {
        let that = this;
        this.$axios
          .post(this.baseURL + "check_password/", that.log_user)
          .then((res) => {
            if (res.data.code === 1) {
              if (res.data.exists) {
                that.$message({
                  message: "登录成功！",
                  type: "success",
                });
                //页面之间的通信
                // JSON.stringify将要序列化成 一个JSON 字符串的值，将值存在sessionStorage读取或保存数据中，设置key值为user
                sessionStorage.setItem("user", JSON.stringify({
							    username: that.log_user.lname,
                  password: that.log_user.lpassword
                  
						    }))
                that.$router.push('/Search_user')
                  
              } else {
                this.$message.error("密码错误！");
              }
            } else {
              console.log(res.data.code);
              this.$message.error("校验密码后端出现异常！！");
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    //注册
    doregist() {
      let that = this;
      this.$axios
        .post(that.baseURL + "add_user/", that.re_user)
        .then((res) => {
          if (res.data.code === 1) {
            //数据给users
            that.users = res.data.data;
            //是否成功
            that.$message({
              message: "注册成功！请点击去登陆",
              type: "success",
            });
          } else {
            //失败
            that.$message.error(res.data.msg);
          }
        })
        .catch(function (err) {
          console.log(err);
          that.$message.error("获取后端添加异常");
        });
    },
    //校验提交修改或注册的表单
    submit_user(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //校验成功（valid为true）后添加或者修改执行
          //需要判断是修改还是增加
          if (this.regist) {
            //执行注册
            this.doregist();
          } else if (this.change) {
            //执行修改密码
            this.dochange();
          } else if (this.login) {
            //执行登录
            this.dologin();
          }
        } else {
          console.log("error submit!!");
          this.$message.error("请输入正确是数据！！");
          return false;
        }
      });
    },
    //实现跳转（注册与登录）
    toggle() {
      //跳转后 校验清空
      this.$refs.re_user.resetFields();
      //跳转之后原来框的内容清空
      this.re_user.id = "";
      this.re_user.checkPassword = "";
      this.re_user.password = "";
      this.re_user.username = "";
      this.re_user.email = "";
      this.log_user.lname = "";
      this.log_user.lpassword = "";
      //去注册，去登入
      this.login = !this.login;
      this.regist = !this.regist;
    },
    //实现跳转（登录与修改密码）
    changes() {
      this.ch_user.n_username = "";
      this.ch_user.n_password = "";
      this.ch_user.npassword = "";
      this.$refs.re_user.resetFields();
      this.$refs.log_user.resetFields();
      this.$refs.ch_user.resetFields();
      this.ch_user.cpassword = "";
      this.login = !this.login;
      this.change = !this.change;
    },
    //修改密码
    dochange() {
      let that = this;
      this.$axios
        .post(that.baseURL + "check_password/", {
          lname: that.ch_user.n_username,
          lpassword: that.ch_user.n_password,
        })
        .then((res) => {
          if (res.data.code === 1) {//说明用户不存在
            if (res.data.exists) {
              if (that.ch_user.npassword === "") {
                that.$message.error("新密码不能为空");
              } else if (that.ch_user.npassword === that.ch_user.n_password) {
                that.$message.error("新密码与原密码不能一样");
              } else if (that.ch_user.cpassword === "") {
                that.$message.error("确认密码不能为空");
              } else if (that.ch_user.npassword !== that.ch_user.cpassword) {
                console.log("!!");
                that.$message.error("确认密码与新密码不一致");
              } else {
                //修改操作
                let that = this;
                this.$axios
                  .post(that.baseURL + "update_password/", that.ch_user)
                  .then((res) => {
                    if (res.data.code === 1) {
                      //数据给users
                      that.users = res.data.data;
                      //是否成功
                      that.$message({
                        message: "修改密码成功！请点击去登陆",
                        type: "success",
                      });
                    } else {
                      //失败
                      that.$message.error(res.data.msg);
                    }
                  })
                  .catch(function (err) {
                    console.log(err);
                    that.$message.error("获取后端添加异常");
                  });
              }
            } else {
              that.$message.error("原密码错误！");
            }
          } else {
            console.log(res.data.code);
            that.$message.error("请输入有效值！！");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
};
</script>
<style>
* {
  margin: 0;
  padding: 0;
}
.back{
  color: #99ffff;
  margin: -90px 0px 0px -450px;
}
.item .el-form-item__label{
    color: white;
    margin: 0px -10px 0px 0px;
}
 
#Login {
  height: 100vh;/*窗口高度height: 100vh;*/
  background-color: white;
  display: flex;
  justify-content: center; /*水平居中*/
  align-items: center; /*垂直居中*/
 background: url(../assets/imagebox/11_.png);
  background-size: cover;
}
.container {
  width: 350px;
  height: 500px;
  position: absolute;
  display: flex;
}
.form-box-right {
  position: absolute;
  width: 350px;
  height: 500px;
  display: flex; /*background-color: white;容器框*/
  justify-content: center; /*所有在属性为form-box的容器里的容器水平居中对齐*/
  align-items: center; /*所有在属性为form-box的容器里的容器垂直居中对齐*/
}
.register-box,
.login-box,
.change_password {
  display: flex; /*容器*/
  flex-direction: column; /*元素垂直排列*/
  align-items: center; /*元素居中#777999*/
  background-color:hsl(0, 3%, 35%);
  border-radius: 1px;
}
#Login input {
  width: 200px;
  letter-spacing: 2px; /*字间距*/
}
.form-box-right button {
  width: 200px;
  background: #99ffff;
  border-radius: 5px;
  padding: 10px;
  color: white;
  border: none;
  margin: 0px 0px 20px 50px;
}
#Login p {
  font-size: 12px;
  letter-spacing: 2px;
  color: #99ffff;
  text-align: center;
  margin: 0px 0px 20px 0px;
}
#Login h2 {
  margin: 10px 0px 20px 0px;
  text-transform: uppercase;
  color: white;
  letter-spacing: 5px;
  font-weight: bold;
}
.form-box-right button:active {
  background: whitesmoke;
  color: gray;
}
#Login p:active {
  color: white;
}
</style>
